<template>
	<view class="content">
		<view class="nav" >
			<view v-for="(item, index) in navList" :key="index" class="nav-item" :class="{ current: tabCurrentIndex === index }" @click="tabClick(index)">{{ item.text }}</view>
		</view>
       <view style="height: 80rpx;"></view>
		<!-- 空白页 -->
		<nodata v-if="!orderList.length" style="margin-top: 30%;"  tips="暂无订单" />
		<!-- 订单列表 -->
		<view v-for="(item, index) in orderList" :key="index" class="order-item" >
			<view class="i-top b-b">
				<text class="order-id">订单编号：{{ item.orderId }}</text>
				<text class="state">{{getSatus(item.orderStatus)}}</text>
				<text class="del-btn iconfont iconshanchu" v-if="item.orderStatus==3||item.orderStatus==4||item.orderStatus==6" @click="delOrder(index)"></text>
			</view>
		
			<scroll-view v-if="item.productList.length > 1" class="goods-box" scroll-x @click="toDetail(item)">
				<view v-for="(goodsItem, goodsIndex) in item.productList" :key="goodsIndex" class="goods-item">
					<image class="goods-img" :src="goodsItem.image" mode="aspectFill"></image>
					<view class="buy-num">
						x {{goodsItem.proSum}} 
					</view>
				</view>
			</scroll-view>
			<view v-if="item.productList.length === 1" class="goods-box-single" v-for="(goodsItem, goodsIndex) in item.productList" :key="goodsIndex" @click="toDetail(item)">
				<image class="goods-img" :src="goodsItem.image" mode="aspectFill"></image>
				<view class="right">
					<text class="title clamp">{{ goodsItem.title }}</text>
					<view class="attr-box clamp"><text v-for="(attrItem,attrIndex) in goodsItem.subList" :key="attrIndex">{{attrItem}}<text v-if="attrIndex<goodsItem.subList.length-1">,</text></text> </view>
					<view class="price">￥{{ goodsItem.price }}<text style="margin-left: 10rpx;">x {{goodsItem.proSum}}</text></view>
				</view>
			</view>
	
				<view class="price-box">
					<text class="num" v-if="item.orderSum">共{{item.orderSum}}件商品，</text>
					实付款
					<text class="price">{{item.orderPrice}}</text>
				</view>
			<view class="action-box b-t">
				<view class="action-btn" hover-class="btn-hover" @click.stop="cancelOrder(index)" v-if="item.orderStatus == 0">取消订单</view>
				<view class="action-btn" hover-class="btn-hover" v-if="item.orderStatus>0 && item.orderStatus<4" @click="toPage('/pages/afterSales/add?opt=group')">申请退款</view>
				<view class="action-btn pay-btn" v-if="item.orderStatus == 0" @click.stop="wxPay(index)">立即支付</view>
				<!-- <view class="action-btn pay-btn" hover-class="btn-hover" v-if="item.orderStatus == 4" @click="toPage('/pages/comment/add?opt=group')">立即评价</view> -->
				<view class="action-btn pay-btn" hover-class="btn-hover" v-if="item.orderStatus == 2">确认收货</view>
				
			</view>
		</view>
		
	</view>
</template>

<script>
export default {
	data() {
		return {
			top:0,
			tabCurrentIndex: 0,
			navList: [
				{
					text: '全部',
					orderStatus:-1,
				},
				{
					text: '已兑换',
					orderStatus:1,
				},	
				{
					text: '已取消',
					orderStatus:2,
				}
			],
			orderList: [],
			page: 1,
			limit:4,
			sumPage:0,
		};
	},
	onLoad(e) {
		this.getWh()
		this.tabCurrentIndex = + e.state
		this.getOrderList()
		this.$on('editOrder',order=>{
			let has = this.orderList.findIndex(e=>e.orderId==order.orderId)
			if(has>-1){
				if(order.orderStatus==this.orderList[has].orderStatus||this.navList[this.tabCurrentIndex].orderStatus==-1){
					this.orderList[has] = order
					this.$forceUpdate()
				}else{
					if(this.orderList.length==1){
						this.orderList = []
					}else{
						this.orderList.splice(has,1)
					}
				}
				
			}
		})
	},
	onReachBottom() {
	   this.moreData()
	},
	methods: {
		async wxPay(k){
			let res = await this.$cloud.callFunction('pay',{
				$url:'unifiedOrder',
				orderId: this.orderList[k].orderId
			})
			if(res.returnCode == 'FAIL'){
				uni.showModal({
					content:res.returnMsg,
					showCancel:false,
					success: (r) => {
						if(r.confirm){
							
						}
					}
				})
			}
			if(res.resultCode!='SUCCESS'){
				uni.showModal({
					content:res.errCodeDes,
					showCancel:false,
					success: (r) => {
						if(r.confirm){
							
						}
					}
				})
				return;
			}
			uni.requestPayment({
				...res.payment,
				success: () => {
					uni.showModal({
						content:'支付成功',
						showCancel:false,
						success: (r) => {
							if(r.confirm){
								this.getOrder(k)
							}
						}
					})
				},
				fail:(err)=>{ console.log(err)
					uni.showModal({
						content:'支付错误',
						showCancel:false,
						success: (r) => {
							if(r.confirm){
								
							}
						}
					})
				}
			})
			
		},
		cancelOrder(k){
		    uni.showModal({
		    	content:'是否取消订单：'+this.orderList[k].orderId+'?',
				confirmText:'确认取消',
				success: (r) => {
					if(r.confirm){
						let productList = this.orderList[k].productList
							new Promise(async (resolve, reject) => {
								let resList = []
								for (let i = 0; i < productList.length; i++) {
									let table = productList[i].subList.length > 0 ? 'mall_product_sku' :'mall_product'
									let where = {}
									if (productList[i].subList.length > 0) {
										where = {
											attrId: productList[i].attrId
										}
									} else {
										where = {
											proId: productList[i].proId,
											isUse:1
										}
									}
									let res = await this.$cloud.incNum(table, where, 'stock', productList[i].proSum)
									resList.push(res ? 1 : 0)
									if (resList.length == productList.length) {
										resolve(resList)
									}
								}
							}).then(async r => {
								let res = await this.$cloud.editData('mall_order',{
									orderId:this.orderList[k].orderId
								},{
									orderStatus:4
								})
								this.$msg(res ? '操作成功！' : '操作失败')
								if(res){
									if(this.navList[this.tabCurrentIndex].orderStatus==-1){
										this.orderList[k].orderStatus = 4
										this.$forceUpdate()
									}else{
										if(this.orderList.length==1){
											this.orderList = []
										}else{
											this.orderList.splice(k,1)
										}
									}
								}
							})
					}
				}
		    })
		},
		async getOrder(k){
			let res = await this.$cloud.getOne('mall_order',{where:{orderId:this.orderList[k].orderId}})
			if(res){
				this.orderList[k] = res
			}
		},
		toDetail(item){
			uni.setStorageSync('orderDetail',item)
			this.$store.commit('set_orderDetail',item)
			this.toPage('/pages/order/detail?orderId='+item.orderId)
		},
		getSatus(opt){
			switch(parseInt(opt)){
				case 0:
				return '待付款'
				break
				case 1:
				return '待发货'
				break
				case 2:
				return '待收货'
				break
				case 3:
				return '已完成'
				break
				case 4:
				return '已取消'
				break
				case 5:
				return '待退款'
				break
				case 6:
				return '已退款'
				break
				case 7:
				return '已拒绝'
				break
			}
		},
		moreData() {
			if (this.page >= this.sumPage) return this.$msg('已经加载完毕!')
			this.page++
			uni.showLoading({
				title: '加载中...'
			})
			this.getOrderList()
		},
		async getOrderList() {
			uni.showLoading({
				title: '加载中...'
			})
			let where = {}
			let orderStatus = this.navList[this.tabCurrentIndex].orderStatus
			if(orderStatus>-1){
				where = {orderStatus}
			}
			let orderList = await this.$cloud.getData('mall_order',{
				where,
				page:this.page,
				limit:this.limit,
				orderBy:['createTime','desc']
			})
			if (orderList.length) {
				if (this.page == 1) {
					let  total = await this.$cloud.getCount('mall_order',where)
					this.sumPage = Math.ceil(total/this.limit)
					this.orderList = orderList
				}else{
					this.orderList = this.orderList.concat(orderList)
				}
			}else{
				this.orderList = []
			}
			setTimeout(()=>{
				uni.hideLoading()
			},500)
		},
		tabClick(index) {
			this.tabCurrentIndex = index;
			this.page = 1
			this.sumPage = 0
			this.getOrderList()
		},
		getWh() {
			uni.getSystemInfo({
				success: (res) => {
					this.top = (res.platform == 'ios' ? 44 : 48) + res.statusBarHeight
				}
			})
		},
		delOrder(k) {
		uni.showModal({
			content:"是否删除订单：" + this.orderList[k].orderId +"?",
			confirmColor:'#F56C6C',
			confirmText:'确认删除',
			success: async (r) => {
				if(r.confirm){	
				  let res = await this.$cloud.delData('mall_order',{_id:this.orderList[k]._id})
				  this.$msg(res?'操作成功！':'操作失败')
				  if(res){
					 if(this.orderList.length==1){
					 	this.orderList = []
					 }else{
					 	this.orderList.splice(k,1)
					 }
				  }
				}
			}
		})
		},
	   toPage(url){
		   uni.navigateTo({
		   	url
		   })
	   },
	   
	}
};
</script>

<style lang="scss">
page,
.content {
	background: #f8f8f8;
	height: 100%;
}


.list-scroll-content {
	height: 100%;
}
.clamp {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}
.nav {
	display: flex;
	height: 40px;
	padding: 0 5px;
	background: #fff;
	box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
	position: fixed;
	left:0;
	width: 100%;
	z-index: 998;
	.nav-item {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		font-size: 15px;
		color: #333;
		position: relative;
		&.current {
			color: $themeColor;
			&:after {
				content: '';
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				width: 44px;
				height: 0;
				border-bottom: 2px solid $themeColor;
			}
		}
	}
}


.order-item {
	display: flex;
	flex-direction: column;
	padding-left: 30upx;
	background: #fff;
	margin-top: 16upx;
	.i-top {
		display: flex;
		align-items: center;
		height: 80upx;
		padding-right: 30upx;
		font-size: 24upx;
		color: #333;
		position: relative;
		border-bottom: 1rpx #eee dashed;
		.order-id {
			flex: 1;
			color: #666;
		}
		.state {
			color: $themeColor;
		}
		.del-btn {
			padding: 10upx 0 10upx 36upx;
			font-size: 32upx;
			color: #888;
			position: relative;
			&:after {
				content: '';
				width: 0;
				height: 30upx;
				border-left: 1px solid #eee;
				position: absolute;
				left: 20upx;
				top: 50%;
				transform: translateY(-50%);
			}
		}
	}
	/* 多条商品 */
	.goods-box { 
		height: 160upx;
		padding: 20upx 0;
		border-bottom: 1rpx #eee dashed;
		white-space: nowrap;
		.goods-item {
			width: 155upx;
			height: 155upx;
			display: inline-block;
			margin-right: 24upx;
			position: relative;
		}
		.buy-num{
			width: 50rpx;
			position: absolute;
			bottom: 0;
			right: 0;
			background: rgba(0,0,0,0.5);
			color: #fff;
			text-align: center;
			font-size: 24rpx;
			border-top-left-radius: 20rpx;
		}
		.goods-img {
			display: block;
			width: 100%;
			height: 100%;
			border-radius: 10rpx;
			box-shadow: 5rpx 5rpx 5rpx #ccc;
		}
	}
	/* 单条商品 */
	.goods-box-single {
		display: flex;
		padding: 20upx 0;
		border-bottom: 1rpx #eee dashed;
		.goods-img {
			display: block;
			width: 120upx;
			height: 120upx;
			border-radius: 10rpx;
			box-shadow: 5rpx 5rpx 5rpx #ccc;
			position: relative;
		}
		
		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			padding: 0 30upx 0 24upx;
			overflow: hidden;
			.title {
				font-size: 26upx;
				color: #333;
				line-height: 1;
			}
			.attr-box {
				font-size: 26upx;
				color: #888;
				padding: 10upx 0;
				width: 100%;
			}
			.price {
				display: flex;
				justify-content: space-between;
				font-size: 26upx;
				color: #333;
			}
		}
	}
	.price-box {
		display: flex;
		justify-content: flex-end;
		align-items: baseline;
		padding: 20upx 30upx;
		font-size: 26upx;
		color: #888;
		border-bottom: 1rpx #eee dashed;
		.num {
			margin: 0 8upx;
			color: #333;
		}
		.price {
			font-size: 32upx;
			color: $themeColor;
			&:before {
				content: '￥';
				font-size: 24upx;
				margin: 0 2upx 0 8upx;
			}
		}
	}
	.action-box {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		height: 100upx;
		position: relative;
		padding-right: 30upx;
	}
	.action-btn {
		float: right;
		height: 60upx;
		line-height: 60upx;
		padding: 0 20rpx;
		margin-left: 24upx;
		text-align: center;
		font-size: 24upx;
		color: #888;
		background: #fff;
		border-radius: 10rpx;
		border: 1rpx #ccc solid;
		&:after {
			border-radius: 100px;
		}
		&.recom {
			background: #fff;
			color: $themeColor;
		}
	}
	.pay-btn {
		background: $themeColor;
		color: #fff;
		border-color: #fff;
	}
}


</style>
